package com.magicode.screen.wxapi;

import java.io.*;
import java.util.*;

import android.content.Intent;
import android.util.Xml;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppContext;
import com.magicode.screen.api.ApiHttpClient;
import com.magicode.screen.api.remote.MgcApi;
import com.magicode.screen.bean.Constants;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.protocol.HttpContext;
import org.xmlpull.v1.XmlPullParser;


public class WXPayActivity extends Activity {

	private static final String TAG = "MicroMsg.SDKSample.WXPayActivity";

	PayReq req;
	final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	Map<String,String> resultunifiedorder;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	//	setContentView(R.layout.wx_pay);
		req = new PayReq();

		msgApi.registerApp(Constants.app_pay_weixin_appid);
		if (!msgApi.isWXAppInstalled()) {
			//提醒用户没有按照微信
			Toast.makeText(this, "没有安装微信,请先安装微信!", Toast.LENGTH_SHORT).show();
			return;
		}else {
//		Button appayBtn = (Button) findViewById(R.id.appay_btn);
//		appayBtn.setOnClickListener(new View.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
			//APP支付生成预支付订单   prepay_id
			GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
			getPrepayId.execute();
//			}
//		});
		}

	}

	/**
	 生成签名
	 */

	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.app_pay_weixin_key);
		

		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",packageSign);
		return packageSign;
	}
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.app_pay_weixin_key);

		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",appSign);
		return appSign;
	}
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<"+params.get(i).getName()+">");


			sb.append(params.get(i).getValue());
			sb.append("</"+params.get(i).getName()+">");
		}
		sb.append("</xml>");

		Log.e("orion",sb.toString());
		return sb.toString();
	}

	private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String,String>> {

		private ProgressDialog dialog;


		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(WXPayActivity.this, "提示", "正在获取预支付订单");
		}

		@Override
		protected void onPostExecute(Map<String,String> result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			resultunifiedorder=result;
			//生成APP微信支付参数
			//	genPayReq();
			Intent intent=getIntent();
			String ruleId=intent.getStringExtra("ruleId");
			if(null!=ruleId && !"".equals(ruleId)) {
				//MgcApi.outerpay(AppContext.getInstance().getLoginUid(), "WeichatPay", "1", mHandler);
				String userToken =  AppContext.getInstance().getProperty("user.userToken");
				MgcApi.outerpay(userToken,AppContext.getInstance().getLoginUid(),  8, mHandler,"WeichatPay");
			}

		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String,String>  doInBackground(Void... params) {

			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs();

			Log.e("orion",entity);

			byte[] buf = WXUtil.httpPost(url, entity);

			String content = new String(buf);
			Log.e("orion", content);
			Map<String,String> xml=decodeXml(content);

			return xml;
		}
	}



	public Map<String,String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName=parser.getName();
				switch (event) {
					case XmlPullParser.START_DOCUMENT:

						break;
					case XmlPullParser.START_TAG:

						if("xml".equals(nodeName)==false){
							//实例化student对象
							xml.put(nodeName,parser.nextText());
						}
						break;
					case XmlPullParser.END_TAG:
						break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			Log.e("orion",e.toString());
		}
		return null;

	}


	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	
	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}
	


	private String genOutTradNo() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	

   //
	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();

		try {
			String	nonceStr = genNonceStr();


			xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Constants.app_pay_weixin_appid));
			packageParams.add(new BasicNameValuePair("body", "传媒家会员"));//商品描述   detail//商品详情
			packageParams.add(new BasicNameValuePair("mch_id", Constants.app_pay_weixin_mch_id));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));//随机字符串
			packageParams.add(new BasicNameValuePair("notify_url", "http://121.40.35.3/test"));//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
			packageParams.add(new BasicNameValuePair("out_trade_no",genOutTradNo()));//商户订单号
			packageParams.add(new BasicNameValuePair("spbill_create_ip","127.0.0.1"));//用户端实际ip
			packageParams.add(new BasicNameValuePair("total_fee", "1"));//订单总金额，单位为分
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));


			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));


		   String xmlstring =toXml(packageParams);

			return xmlstring;

		} catch (Exception e) {
//			Log.e(TAG, "genProductArgs fail, ex = " + e.getMessage());
			return null;
		}
		


	}
	private void genPayReq() {

		req.appId = Constants.app_pay_weixin_appid;
		req.partnerId = Constants.app_pay_weixin_mch_id;
		req.prepayId = resultunifiedorder.get("prepay_id");
		req.packageValue = "Sign=WXPay";
		req.nonceStr = genNonceStr();
		req.timeStamp = String.valueOf(genTimeStamp());

		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

		req.sign = genAppSign(signParams);

		Log.e("orion", signParams.toString());

	}
	private void sendPayReq() {
		

		msgApi.registerApp(Constants.app_pay_weixin_appid);
		msgApi.sendReq(req);
	}


	private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			try {
				AsyncHttpClient client = ApiHttpClient.getHttpClient();

				HttpContext httpContext = client.getHttpContext();
				ObjectMapper mapper = new ObjectMapper();
				Map result = mapper.readValue(arg2, HashMap.class);
				String status = (String)result.get("status");
				if("success".equals(status)){
					String buyhistoryid = (String)result.get("buyhistoryid");
					//将json字符串转成map结合解析出来，并打印(这里以解析成map为例)
					Map readyToPay = (Map)result.get("readyToPay");
					String timestamp = (String)readyToPay.get("timestamp");
					String sign = (String)readyToPay.get("sign");
					String partnerid = (String)readyToPay.get("partnerid");
					String noncestr = (String)readyToPay.get("noncestr");
					String prepayid = (String)readyToPay.get("prepayid");
					String paypackage = (String)readyToPay.get("package");
					String appid = (String)readyToPay.get("appid");
					req.appId =appid;
					req.partnerId = partnerid;
					req.prepayId = prepayid;
					req.packageValue =paypackage;
					req.nonceStr = noncestr;
					req.timeStamp = timestamp;
					req.sign =sign;


					sendPayReq();//调起微信支付
				}


			} catch (Exception e) {
				e.printStackTrace();
				onFailure(arg0, arg1, arg2, e);
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							  Throwable arg3) {
	//		AppContext.showToast(R.string.tip_error_for_network);
		}
	};
	public void finish() {
		super.finish();
	}

	protected void onDestroy() {
		super.onDestroy();
	}
}

